﻿using ChuanYe.CountyFireManagement.EF.MySQL;
using ChuanYe.CountyFireManagement.EF.MySQL.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ChuanYe.CountyFireManagement.BLL
{
    public class FireExpireBLL
    {
        #region 构造单例
        private FireExpireBLL() { }
        private static FireExpireBLL _instance;
        public static FireExpireBLL Instance
        {
            get
            {
                return _instance ?? (_instance = new FireExpireBLL());
            }
        }
        #endregion

        public List<Fireexpire> Get() 
        {
            using (CountyFireManagementContext ef = new CountyFireManagementContext())
            {
                return ef.Fireexpire.ToList();
            }
        }

        public int Count() 
        {
            using (CountyFireManagementContext ef = new CountyFireManagementContext())
            {
                return ef.Fireexpire.Count();
            }
        }

        public List<Fireexpire> GetUnExpire(int fireId=0)
        {
            using (CountyFireManagementContext ef = new CountyFireManagementContext())
            {
                var nowDateTime = DateTime.Now;
                string sql = "SELECT * FROM fireexpire as a WHERE 1=1 AND '{0}' > (DATE_ADD(a.StartTime,INTERVAL a.Value MINUTE))";
                sql = string.Format(sql, nowDateTime);
                if (fireId > 0)
                {
                    sql += " AND a.FireID = '{0}'";
                    sql = string.Format(sql, fireId);
                }
                var list = ef.Database.SqlQuery<Fireexpire>(sql);
                return list;
            }
        }

        public dynamic GetExpire(int fireId = 0)
        {
            var list = GetUnExpire(fireId);
            using (CountyFireManagementContext ef = new CountyFireManagementContext())
            {
                var result = ef.Fireexpire.Where(p => p.FireId == fireId).OrderByDescending(o => o.ExpireId).ToList().Select(s=>new {
                                 s.ExpireId,
                                 s.FireId,
                                 s.MessageContent,
                                 s.MessageType,
                                 s.RecordType,
                                 s.StartTime,
                                 s.Value,
                                 IsExpire=list.Where(p=>p.ExpireId==s.ExpireId).FirstOrDefault()==null?0:1,
                                 ServerTime=DateTime.Now
                             }).FirstOrDefault();
                return result;
            }
        }
    }
}
